package org.dromara.common.core.utils;

import cn.hutool.core.map.MapUtil;
import lombok.extern.log4j.Log4j2;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@Log4j2
public class WeChatRobot {

    private static final String WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=1a4547e3-f510-402f-a3f5-ec59a191b4de";

    public static void main(String[] args) {
        try {
//            sendTextMessage("Hello, this is a text message.", new String[]{"lus"}, new String[]{"15522899559"});
//            sendTextMessage("Hello, this is a text message.", new String[]{"15522899559","13292706730","@all"});
//            sendMarkdownMessage("Real-time user feedback <font color=\"warning\">132 cases</font>, please pay attention.\n > Type: <font color=\"comment\">User Feedback</font>\n > Normal User Feedback: <font color=\"comment\">117 cases</font>\n > VIP User Feedback: <font color=\"comment\">15 cases</font>", new String[]{"lus"}, new String[]{"15522899559"});
            sendMarkdownMessage("Hello, this is a text message.", MapUtil.builder("ttt", "abc<@all>").map(), "15522899559,@all");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendTextMessage(String content) throws Exception {
        sendTextMessage(content, null, null);
    }

    public static void sendTextMessage(String content, String[] mentionedMobileList) throws Exception {
        sendTextMessage(content, null, mentionedMobileList);
    }

    private static void sendTextMessage(String content, String[] mentionedList, String[] mentionedMobileList) throws Exception {
        URL url = new URL(WEBHOOK_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; utf-8");
        connection.setDoOutput(true);

        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{ \"msgtype\": \"text\", ");
        jsonBuilder.append("\"text\": { \"content\": \"").append(content).append("\"");

        if (mentionedList != null && mentionedList.length > 0) {
            jsonBuilder.append(", \"mentioned_list\": [\"");
            for (int i = 0; i < mentionedList.length; i++) {
                jsonBuilder.append(mentionedList[i]);
                if (i < mentionedList.length - 1) {
                    jsonBuilder.append("\", \"");
                }
            }
            jsonBuilder.append("\"]");
        }

        if (mentionedMobileList != null && mentionedMobileList.length > 0) {
            jsonBuilder.append(", \"mentioned_mobile_list\": [\"");
            for (int i = 0; i < mentionedMobileList.length; i++) {
                jsonBuilder.append(mentionedMobileList[i]);
                if (i < mentionedMobileList.length - 1) {
                    jsonBuilder.append("\", \"");
                }
            }
            jsonBuilder.append("\"]");
        }

        jsonBuilder.append("} }");

        String jsonString = jsonBuilder.toString();
        log.info(jsonString);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);
    }

    public static void sendMarkdownMessage(String webhook, String header, List<String> items) {
        String body = MarkdownUtil.createOrderedList(items);
        sendMarkdownMessage(webhook, header + body);
    }

    public static void sendMarkdownMessage(String header, Map<String, String> body, String mentionedMobileList) {
        String titleLink = MarkdownUtil.createLink(header, "http://192.168.88.31:15003/pm/require");
        String headerTitle = MarkdownUtil.createHeaderN(1, titleLink);
        String bodyM = MarkdownUtil.createMap(body);
        try {
            sendMarkdownMessage(headerTitle + bodyM, null, StringUtils.split(mentionedMobileList, ","));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendMarkdownMessage(String msgType, String title, Map<String, String> body, String mentionedMobileList) {
        String headerTitle = MarkdownUtil.createHeaderN(1, msgType + ": " + title);
        String bodyM = MarkdownUtil.createMap(body);
        try {
            sendMarkdownMessage(headerTitle + bodyM, null, StringUtils.split(mentionedMobileList, ","));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendMarkdownMessage(String webhook, String content) {
        try {
            URL url = new URL(webhook);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setDoOutput(true);

            String jsonString = "{ \"msgtype\": \"markdown\", " +
                    "\"markdown\": { \"content\": \"" + content + "\"" +
                    "} }";
            log.info(jsonString);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void sendMarkdownMessage(String content, String[] mentionedList, String[] mentionedMobileList) throws Exception {
        URL url = new URL(WEBHOOK_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; utf-8");
        connection.setDoOutput(true);

        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{ \"msgtype\": \"markdown\", ");
        jsonBuilder.append("\"markdown\": { \"content\": \"").append(content).append("\"");

        if (mentionedList != null && mentionedList.length > 0) {
            jsonBuilder.append(", \"mentioned_list\": [\"");
            for (int i = 0; i < mentionedList.length; i++) {
                jsonBuilder.append(mentionedList[i]);
                if (i < mentionedList.length - 1) {
                    jsonBuilder.append("\", \"");
                }
            }
            jsonBuilder.append("\"]");
        }

        if (mentionedMobileList != null && mentionedMobileList.length > 0) {
            jsonBuilder.append(", \"mentioned_mobile_list\": [\"");
            for (int i = 0; i < mentionedMobileList.length; i++) {
                jsonBuilder.append(mentionedMobileList[i]);
                if (i < mentionedMobileList.length - 1) {
                    jsonBuilder.append("\", \"");
                }
            }
            jsonBuilder.append("\"]");
        }

        jsonBuilder.append("} }");

        String jsonString = jsonBuilder.toString();
        log.info(jsonString);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);
    }

}



